<?php


namespace app\partneradmin\controller;


use app\admin\model\CustomerServiceAccountMiddle;
use app\admin\model\CustomerServiceGroup;
use app\admin\model\CustomerServicePersonnel;
use app\partneradmin\model\CustomerServiceAccount;
use app\partneradmin\model\Order;
use app\partneradmin\model\User;
use app\common\controller\partneradmin\Base;

class Statistics extends Base
{
    public function statisticsFrom()
    {

        //设置初始返回
        $list = [];
        //已分配用户搜索条件
        $distributionUserWhere = [

        ];
        //联系客服的用户数搜索条件
        $contactUserWhere = [
            'is_check_kf_switch' => 1
        ];
        //系统支付页面数量
        $sysPayViewWhere = [
            'generate_type' => 1,
            'status' => 3
        ];
        //系统订单支付金额
        $sysOrderWhere = [
            'generate_type' => 1,
            'status' => 3
        ];
        //人工支付页面数量
        $artificialPayViewWhere = [
            'generate_type' => 2,
            'status' => 3
        ];
        //人工支付订单金额
        $artificialOrderWhere = [
            'generate_type' => 2,
            'status' => 3
        ];
        //所有客服列表
        $personnelWhere = [
            'is_del' => 0,
        ];
        $personnelAccountWhere = [
            'is_del' => 0,
//            'switch' => 1,
        ];
        $adminCustomerServiceInfo = $this->getCustomerServiceInfo();
        switch ($this->admin['rule']) {
            case 1:
                $customerServiceGroupId = $adminCustomerServiceInfo['customer_service_personnel_info']['customer_service_group_id'];
                break;
            case 2:
                $customerServicePersonnelId = $adminCustomerServiceInfo['customer_service_personnel_info']['id'];
                break;
        }
        //所有账号列表
        $accountWhere = [
            'status' => 1,
            'is_del' => 0,
            'switch' => 1
        ];
        $partner_id = $this->admin['partner_id'];
        $accountWhere['partner_id'] = $partner_id;
        $personnelWhere['partner_id'] = $this->admin['partner_id'];
        $personnelAccountWhere['partner_id'] = $this->admin['partner_id'];
        $sysPayViewWhere['partner_id'] = $partner_id;
        $sysOrderWhere['partner_id'] = $partner_id;
        $artificialPayViewWhere['partner_id'] = $partner_id;
        $artificialOrderWhere['partner_id'] = $partner_id;
        $startOpenTime = $this->request->post('start_time', date('Y-m-d', time()) . '00:00:00');
        $endOpenTime = $this->request->post('end_time', date('Y-m-d', time()) . '23:59:59');
        $serviceGroupName = $this->request->post('customer_service_group_name', '');
        $servicePersonnelName = $this->request->post('customer_service_personnel_name', '');
        $serviceAccountName = $this->request->post('customer_service_account_name', '');
        $order = $this->request->post('order', 'total_amount');
        $sort = $this->request->post('sort', 'SORT_DESC');
        $appBaseId = $this->request->post('app_base_id', '');
        if ($appBaseId != '') {
            $accountWhere['app_base_id'] = $appBaseId;
            $personnelAccountWhere['app_base_id'] = $appBaseId;
            $distributionUserWhere['app_base_id'] = $appBaseId;
            $contactUserWhere['app_base_id'] = $appBaseId;
            $sysPayViewWhere['app_base_id'] = $appBaseId;
            $sysOrderWhere['app_base_id'] = $appBaseId;
            $artificialPayViewWhere['app_base_id'] = $appBaseId;
            $artificialOrderWhere['app_base_id'] = $appBaseId;
        } else {
            $this->error('未选择app!');
        }
        if ($serviceGroupName != '') {
            $groupInfo = \app\partneradmin\model\CustomerServiceGroup::get(['name' => $serviceGroupName]);
            if (empty($groupInfo)) {
                $this->success('列表', '', $list);
            }
            $accountWhere['customer_service_group_id'] = $groupInfo['id'];
        }
        //查找客服人员
        if ($servicePersonnelName != '') {
            $personnelInfo = \app\partneradmin\model\CustomerServicePersonnel::get(['name' => $servicePersonnelName]);
            if (empty($personnelInfo)) {
                $this->success('列表', '', $list);
            }
            $accountWhere['customer_service_personnel_id'] = $personnelInfo['id'];
            $personnelAccountWhere['customer_service_personnel_id'] = $personnelInfo['id'];
            $personnelWhere['id'] = $personnelInfo['id'];
        }
        //查找客服账号
        if ($servicePersonnelName != '') {
            $this->error('多账号不支持客服账号查找!');
//            $personnelInfo = \app\partneradmin\model\CustomerServicePersonnel::get(['name' => $servicePersonnelName]);
//            if (empty($personnelInfo)) {
//                $this->success('列表', '', $list);
//            }
//            $accountWhere['username'] = $serviceAccountName;
        }
        if (!empty($customerServicePersonnelId)) {
            $accountWhere['customer_service_personnel_id'] = $customerServicePersonnelId;
            $personnelAccountWhere['customer_service_personnel_id'] =$customerServicePersonnelId;
            $personnelWhere['id'] = $customerServicePersonnelId;
        }
        if (!empty($customerServiceGroupId)) {
            $accountWhere['customer_service_group_id'] = $customerServiceGroupId;
            $personnelAccountWhere['customer_service_group_id'] =$customerServiceGroupId;
            $personnelWhere['customer_service_group_id'] = $customerServiceGroupId;
        }
        //时间筛选（范围）
        if ($startOpenTime != '' && $endOpenTime != '') {
            $startOpenTime = strtotime($startOpenTime . '00:00:00');//格式化开始时间
            $endOpenTime = strtotime($endOpenTime . '23:59:59');//格式化结束时间
            $distributionUserWhere['create_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $contactUserWhere['create_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $sysPayViewWhere['update_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $sysOrderWhere['pay_success_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $artificialPayViewWhere['update_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $artificialOrderWhere['pay_success_time'] = ['between', [$startOpenTime, $endOpenTime]];
        }

        $country_config_id = $this->request->post('country_config_id', '');
        if (empty($country_config_id)) {
            $country_name = '未知';
        } else {
            if ($country_config_id == 1) {
                $country_name = '印度';
            } else {
                $country_name = '墨西哥';
            }
            $distributionUserWhere['country_config_id'] = $country_config_id;
            $contactUserWhere['country_config_id'] = $country_config_id;
            $sysPayViewWhere['country_config_id'] = $country_config_id;
            $sysOrderWhere['country_config_id'] = $country_config_id;
            $artificialPayViewWhere['country_config_id'] = $country_config_id;
            $artificialOrderWhere['country_config_id'] = $country_config_id;
        }
//        $accountList = CustomerServiceAccount::with(['CustomerServiceAccountMiddle', 'CustomerServicePersonnel', 'CustomerServiceGroup', 'Partner'])->where($accountWhere)->select()->toArray();
        $personnelList = CustomerServicePersonnel::with(['CustomerServiceGroup', 'Partner'])->where($personnelWhere)->select()->toArray();

        //已分配用户数
        $distributionUserList = User::field('count(id) as user_num,customer_service_account_middle_id')
            ->where($distributionUserWhere)
            ->group('customer_service_account_middle_id')
            ->select();
        $distributionUserList = empty($distributionUserList) ? [] : array_column($distributionUserList->toArray(), null, 'customer_service_account_middle_id');

        //联系客服的用户数
        $contactUserList = User::field('count(id) as user_num,customer_service_account_middle_id')
            ->where($contactUserWhere)
            ->group('customer_service_account_middle_id')
            ->select();
        $contactUserList = empty($contactUserList) ? [] : array_column($contactUserList->toArray(), null, 'customer_service_account_middle_id');

        //系统支付页面数量
        $sysPayViewList = \app\partneradmin\model\PayView::field('count(id) as pay_view_num,customer_service_personnel_id')
            ->where($sysPayViewWhere)
            ->group('customer_service_personnel_id')
            ->select();
        $sysPayViewList = empty($sysPayViewList) ? [] : array_column($sysPayViewList->toArray(), null, 'customer_service_personnel_id');

        //系统订单支付金额
        $sysOrderList = Order::field('sum(real_amount) as order_amount,customer_service_personnel_id')
            ->where($sysOrderWhere)
            ->group('customer_service_personnel_id')
            ->select();
        $sysOrderList = empty($sysOrderList) ? [] : array_column($sysOrderList->toArray(), null, 'customer_service_personnel_id');

        //人工支付页面数量
        $artificialPayViewList = \app\partneradmin\model\PayView::field('count(id) as pay_view_num,customer_service_personnel_id')
            ->where($artificialPayViewWhere)
            ->group('customer_service_personnel_id')
            ->select();
        $artificialPayViewList = empty($artificialPayViewList) ? [] : array_column($artificialPayViewList->toArray(), null, 'customer_service_personnel_id');

        //人工支付订单金额
        $artificialOrderList = Order::field('sum(real_amount) as order_amount,customer_service_personnel_id')
            ->where($artificialOrderWhere)
            ->group('customer_service_personnel_id')
            ->select();
        $artificialOrderList = empty($artificialOrderList) ? [] : array_column($artificialOrderList->toArray(), null, 'customer_service_personnel_id');

        //最终返回数据 空数组自定义

        foreach ($personnelList as $value) {
            $personnelAccountWhere['customer_service_personnel_id'] = $value['id'];
            $personnelAccountList = \app\admin\model\CustomerServiceAccount::with(['CustomerServiceAccountMiddle'])->where($personnelAccountWhere)->select()->toArray();
            $personnelAccountNum = CustomerServiceAccount::with(['CustomerServiceAccountMiddle'])->where($personnelAccountWhere)->count();
            if (empty($personnelAccountNum)) {
                continue;
            }
            $distribution_user_num = 0;
            $contact_service_personnel_num = 0;

            foreach ($personnelAccountList as $v) {
                $distribution_user_num = $distribution_user_num + (empty($distributionUserList[$v['customer_service_account_middle_id']]) ? 0 : $distributionUserList[$v['customer_service_account_middle_id']]['user_num']);
                $contact_service_personnel_num = $contact_service_personnel_num + (empty($contactUserList[$v['customer_service_account_middle_id']]) ? 0 : $contactUserList[$v['customer_service_account_middle_id']]['user_num']);
            }
            $info = [
                'account_name' => $personnelAccountNum . '个',
                'partner_name' => $value['partner_name'],
                'group_name' => $value['group_name'],
                'personnel_name' => $value['name'],
                'distribution_user_num' => $distribution_user_num,
                'contact_service_personnel_num' => $contact_service_personnel_num,
                'sys_pay_view_num' => empty($sysPayViewList[$value['id']]) ? 0 : $sysPayViewList[$value['id']]['pay_view_num'],
                'sys_order_amount' => empty($sysOrderList[$value['id']]) ? 0 : $sysOrderList[$value['id']]['order_amount'],
                'artificial_pay_view_num' => empty($artificialPayViewList[$value['id']]) ? 0 : $artificialPayViewList[$value['id']]['pay_view_num'],
                'artificial_order_amount' => empty($artificialOrderList[$value['id']]) ? 0 : $artificialOrderList[$value['id']]['order_amount'],
            ];
            //计算总金额
            $info['total_amount'] = $info['sys_order_amount'] + $info['artificial_order_amount'];
            $info['country_name'] = $country_name;
            //计算人均
            if (empty($info['total_amount']) || empty($info['distribution_user_num'])) {
                $info['per_amount'] = 0;
            } else {
                $info['per_amount'] = round($info['total_amount'] / $info['distribution_user_num'], 2);
            }
            $list[] = $info;
        }
        $order = empty($order) ? 'total_amount' : $order;
        $sort = empty($sort) ? 'SORT_DESC' : $sort;
        $list = arraySequence($list, $order, $sort);
        $totalInfo = [
            'distribution_user_num_total' => 0,
            'contact_service_personnel_num_total' => 0,
            'sys_pay_view_num_total' => 0,
            'sys_order_amount_total' => 0,
            'artificial_pay_view_num_total' => 0,
            'artificial_order_amount_total' => 0,
            'total_amount_total' => 0,
            'per_amount_total' => 0,
        ];
        if (!empty($list)) {
            $totalInfo['distribution_user_num_total'] = array_sum(array_column($list, 'distribution_user_num'));
            $totalInfo['contact_service_personnel_num_total'] = array_sum(array_column($list, 'contact_service_personnel_num'));
            $totalInfo['sys_pay_view_num_total'] = array_sum(array_column($list, 'sys_pay_view_num'));
            $totalInfo['sys_order_amount_total'] = array_sum(array_column($list, 'sys_order_amount'));
            $totalInfo['artificial_pay_view_num_total'] = array_sum(array_column($list, 'artificial_pay_view_num'));
            $totalInfo['artificial_order_amount_total'] = array_sum(array_column($list, 'artificial_order_amount'));
            $totalInfo['total_amount_total'] = array_sum(array_column($list, 'total_amount'));
            if (empty($totalInfo['total_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['per_amount_total'] = 0;
            } else {
                $totalInfo['per_amount_total'] = round($totalInfo['total_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
        }
        $data = [
            'list' => $list,
            'total' => $totalInfo
        ];
        $this->success('获取成功', '', $data);
    }

    //查看当日已分配用户数
    public static function getAssignedUserNum($accountList)
    {
        $assigned_user_num = 0;
        $startOpenTime = strtotime(date('Y-m-d', time()) . '00:00:00');//格式化开始时间
        $endOpenTime = strtotime(date('Y-m-d', time()) . '23:59:59');//格式化结束时间
        if (!empty($accountList)) {
            $accountList = $accountList->toArray();
            $accountMiddleIds = array_column($accountList, 'customer_service_account_middle_id');
            $assigned_user_num = \app\admin\model\User::where([
                'customer_service_account_middle_id' => ['in', $accountMiddleIds],
                'create_time' => ['between', [$startOpenTime, $endOpenTime]]
            ])
                ->count('id');
        }
        return $assigned_user_num;
    }

    /**
     * 首页统计  用户数 合作团队数  客服人员数 客服账号数  今日登录数  今日注册数  三日新增数  七日新增数  七日活跃 月活跃
     */
    public function getIndexStatistics()
    {
        $data = [];
        //当天的开始时间 结束时间
        $startOpenTime = date('Y-m-d', time());
        $endOpenTime = date('Y-m-d', time());

        $startOpenTime = strtotime($startOpenTime . '00:00:00');//格式化开始时间
        $endOpenTime = strtotime($endOpenTime . '23:59:59');//格式化结束时间
        //三日前的开始时间
        $threeStartTime = strtotime(date('Y-m-d', strtotime('-3 day')) . '00:00:00');
        //七日前的开始时间
        $sevenStartTime = strtotime(date('Y-m-d', strtotime('-7 day')) . '00:00:00');
        //本月的开始时间
        $monthStartTime = mktime(0, 0, 0, date('m'), 1, date('Y'));
        //首页统计  用户数 合作团队数  客服人员数 客服账号数  今日登录数  今日注册数  三日新增数  七日新增数  七日活跃 月活跃
        //总用户数
        $data['total_user_num'] = User::field('id')->count('id');
        //合作团队总数
        $partner_where = [
            'is_del' => 0
        ];
        $data['total_partner_num'] = \app\partneradmin\model\Partner::field('id')->where($partner_where)->count();
        //客服人员总数
        $service_personnel_where = [
            'is_del' => 0
        ];
        $data['total_service_personnel_num'] = \app\partneradmin\model\CustomerServicePersonnel::field('id')->where($service_personnel_where)->count();
        //客服账号数量
        $service_account_where = [
            'is_del' => 0
        ];
        $data['total_service_account_num'] = CustomerServiceAccount::field('id')->where($service_account_where)->count();
        //今日登录数量
        $today_user_login_where = [
            'logintime' => ['between', [$startOpenTime, $endOpenTime]]
        ];
        $data['today_user_login_num'] = User::field('id')->where($today_user_login_where)->count();
        //今日注册数量
        $today_user_register_where = [
            'create_time' => ['between', [$startOpenTime, $endOpenTime]]
        ];
        $data['today_user_register_num'] = User::field('id')->where($today_user_register_where)->count();
        //三日新增
        $three_user_register_where = [
            'create_time' => ['between', [$threeStartTime, $endOpenTime]]
        ];
        $data['three_user_register_num'] = User::field('id')->where($three_user_register_where)->count();
        //七日新增
        $seven_user_register_where = [
            'create_time' => ['between', [$sevenStartTime, $endOpenTime]]
        ];
        $data['seven_user_register_num'] = User::field('id')->where($seven_user_register_where)->count();
        //七日活跃
        $seven_user_active_where = [
            'prevtime' => ['between', [$sevenStartTime, $endOpenTime]]
        ];
        $data['seven_user_active_num'] = User::field('id')->where($seven_user_active_where)->count();
        //月活跃
        $month_user_active_where = [
            'prevtime' => ['between', [$monthStartTime, $endOpenTime]]
        ];
        $data['month_user_active_num'] = User::field('id')->where($month_user_active_where)->count();
        $this->success('获取成功', '', $data);
    }

    /**
     * 折线图统计
     */
    public function getBrokenLineStatistics()
    {
        //折线图统计
        $list = [
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-6 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-6 day')) . '23:59:59'),
                'name' => 'seven'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-5 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-5 day')) . '23:59:59'),
                'name' => 'six'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-4 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-4 day')) . '23:59:59'),
                'name' => 'five'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-3 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-3 day')) . '23:59:59'),
                'name' => 'four'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-2 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-2 day')) . '23:59:59'),
                'name' => 'three'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-1 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-1 day')) . '23:59:59'),
                'name' => 'two'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', time()) . '00:00:00'),  //今天的开始时间
                'end_time' => strtotime(date('Y-m-d', time()) . '23:59:59'),   //今天的结束时间,
                'name' => 'one'
            ]
        ];

        $data = [];
        $loginData = [];
        $registerData = [];
        foreach ($list as $val) {
            $loginWhere = [
                'logintime' => ['between', [$val['start_time'], $val['end_time']]]
            ];
            $loginData[] = User::field('id')->where($loginWhere)->count();
            $registerWhere = [
                'create_time' => ['between', [$val['start_time'], $val['end_time']]]
            ];
            $registerData[] = User::field('id')->where($registerWhere)->count();
            $data[] = $val['name'];
        }
        $info = [
            'login_data' => $loginData,
            'register_data' => $registerData,
            'x_axis' => $data
        ];
        $this->success('获取成功', '', $info);
    }

    //单独人员统计
    public function personnelStatistics()
    {
        $list = [];
        $totalInfo = [
            'distribution_user_num_total' => 0,
            'sys_pay_view_num_total' => 0,
            'sys_order_amount_total' => 0,
            'artificial_pay_view_num_total' => 0,
            'artificial_order_amount_total' => 0,
            'total_amount_total' => 0,
            'artificial_per_amount_total' => 0,
            'per_amount_total' => 0,
        ];
        //人员名字
        $name = $this->request->post('name', '');
        if (empty($name)) {
            $data = [
                'list' => $list,
                'total' => $totalInfo
            ];
            $this->success('获取成功', '', $data);
        }
        $appBaseId = $this->request->post('app_base_id', '');
        if ($appBaseId == '') {
            $this->error('未选择app!');
        }
        //时间
        $startOpenTime = $this->request->post('start_time', date('Y-m-d', time()));
        $endOpenTime = $this->request->post('end_time', date('Y-m-d', time()));
        $row = CustomerServicePersonnel::get(['name' => $name, 'partner_id' => $this->admin['partner_id']]);
        if (empty($row)) {
            $this->error('用户不存在!');
        }
        $list = $this->getPersonnelStatisticsInfo($row['id'], $startOpenTime, $endOpenTime,$appBaseId);
        if (!empty($list)) {
            $totalInfo['distribution_user_num_total'] = array_sum(array_column($list, 'distribution_user_num'));
            $totalInfo['sys_pay_view_num_total'] = array_sum(array_column($list, 'sys_pay_view_num'));
            $totalInfo['sys_order_amount_total'] = array_sum(array_column($list, 'sys_order_amount'));
            $totalInfo['artificial_pay_view_num_total'] = array_sum(array_column($list, 'artificial_pay_view_num'));
            $totalInfo['artificial_order_amount_total'] = array_sum(array_column($list, 'artificial_order_amount'));
            $totalInfo['total_amount_total'] = array_sum(array_column($list, 'total_amount'));
            if (empty($totalInfo['artificial_order_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['artificial_per_amount_total'] = 0;
            } else {
                $totalInfo['artificial_per_amount_total'] = round($totalInfo['artificial_order_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
            if (empty($totalInfo['total_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['per_amount_total'] = 0;
            } else {
                $totalInfo['per_amount_total'] = round($totalInfo['total_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
        }
        $data = [
            'list' => $list,
            'total' => $totalInfo
        ];
        $this->success('获取成功', '', $data);
    }

    //获取人员统计详情
    public function getPersonnelStatisticsInfo($id, $startOpenTime, $endOpenTime,$appBaseId)
    {
//        $accountInfo = \app\admin\model\CustomerServiceAccount::field('id')->where([
//            'customer_service_personnel_id' => $id,
//            'partner_id' => $this->admin['partner_id'],
//            'switch' => 1,
//            'app_base_id' => $appBaseId
//
//        ])
//            ->find();
//        if (empty($accountInfo)) {
//            $this->error('当前客服未添加客服账号');
//        }
//        $accountMiddleInfo = CustomerServiceAccountMiddle::where([
//            'customer_service_account_id' => $accountInfo['id']
//        ])
//            ->find();
        $accountInfo = \app\admin\model\CustomerServiceAccount::field('id')->where([
            'customer_service_personnel_id' => $id,
            'partner_id' => $this->admin['partner_id'],
            'switch' => 1,
            'app_base_id' => $appBaseId

        ])
            ->select();
        if (empty($accountInfo)) {
            $this->error('当前客服未添加客服账号');
        }
        $accountInfo = $accountInfo->toArray();
        $accountIds = array_column($accountInfo,  'id');
        $accountMiddleInfo = CustomerServiceAccountMiddle::where([
            'customer_service_account_id' => ['in',$accountIds]
        ])
            ->select()->toArray();
        $accountMiddleIds = array_column($accountMiddleInfo,  'id');
        //获取两个日期
        $dateList = printDates($startOpenTime, $endOpenTime);
        $list = [];
        foreach ($dateList as $value) {
            $info['date'] = $value['date'];
            //已分配客服数
//            $distributionUserWhere = [
//                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
//                'customer_service_account_middle_id' => $accountMiddleInfo['id'],
//                'app_base_id' => $appBaseId
//            ];
            $distributionUserWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_account_middle_id' =>  ['in',$accountMiddleIds],
                'app_base_id' => $appBaseId
            ];
            $info['distribution_user_num'] = \app\partneradmin\model\User::where($distributionUserWhere)->count('id');
            //系统生成支付页面
            $sysPayViewWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_personnel_id' => $id,
                'generate_type' => 1,
                'app_base_id' => $appBaseId
            ];
            $info['sys_pay_view_num'] = \app\partneradmin\model\PayView::where($sysPayViewWhere)->count('id');
            //系统订单支付金额
            $sysOrderWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'generate_type' => 1,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['sys_order_amount'] = \app\partneradmin\model\Order::where($sysOrderWhere)->sum('real_amount');
            //人工生成支付页面
            $artificialPayViewWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_personnel_id' => $id,
                'generate_type' => 2,
                'app_base_id' => $appBaseId
            ];
            $info['artificial_pay_view_num'] = \app\partneradmin\model\PayView::where($artificialPayViewWhere)->count('id');;
            //人工支付订单金额
            $artificialOrderWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_personnel_id' => $id,
                'generate_type' => 2,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['artificial_order_amount'] = Order::where($artificialOrderWhere)->sum('real_amount');
            //计算总金额
            $info['total_amount'] = $info['sys_order_amount'] + $info['artificial_order_amount'];
            //计算人工订单人均
            if (empty($info['artificial_order_amount']) || empty($info['distribution_user_num'])) {
                $info['artificial_per_amount'] = 0;
            } else {
                $info['artificial_per_amount'] = round($info['artificial_order_amount'] / $info['distribution_user_num'], 2);
            }
            //计算人均
            if (empty($info['total_amount']) || empty($info['distribution_user_num'])) {
                $info['per_amount'] = 0;
            } else {
                $info['per_amount'] = round($info['total_amount'] / $info['distribution_user_num'], 2);
            }
            $list[] = $info;
        }
        return $list;
    }

    //客服组统计
    public function groupStatistics()
    {
        $list = [];
        $totalInfo = [
            'distribution_user_num_total' => 0,
            'sys_pay_view_num_total' => 0,
            'sys_order_amount_total' => 0,
            'artificial_pay_view_num_total' => 0,
            'artificial_order_amount_total' => 0,
            'total_amount_total' => 0,
            'artificial_per_amount_total' => 0,
            'per_amount_total' => 0,
        ];
        //客服组名字
        $name = $this->request->post('name', '');
        //app
        $appBaseId = $this->request->post('app_base_id', '');
        if ($appBaseId == '') {
            $this->error('未选择app!');
        }
        //时间
        $startOpenTime = $this->request->post('start_time', date('Y-m-d', time()));
        $endOpenTime = $this->request->post('end_time', date('Y-m-d', time()));
        if (empty($name)) {
            $data = [
                'list' => $list,
                'total' => $totalInfo
            ];
            $this->success('获取成功', '', $data);
        }
        $row = CustomerServiceGroup::get(['name' => $name, 'partner_id' => $this->admin['partner_id']]);
        if (empty($row)) {
            $this->error('客服组不存在!');
        }
        //查找客服组下所有的打开的客服账号
        $accountList = CustomerServiceAccount::with(['CustomerServiceAccountMiddle'])
            ->where([
                'switch' => 1,
                'customer_service_group_id' => $row['id']
            ])->select();
        if (empty($accountList)) {
            $this->error('客服组下无使用中的账号!');
        }
        $accountMiddleIds = array_column($accountList->toArray(), 'customer_service_account_middle_id');
        $list = $this->getGroupStatisticsInfo($row['id'], $accountMiddleIds, $startOpenTime, $endOpenTime,$appBaseId);
        if (!empty($list)) {
            $totalInfo['distribution_user_num_total'] = array_sum(array_column($list, 'distribution_user_num'));
            $totalInfo['sys_pay_view_num_total'] = array_sum(array_column($list, 'sys_pay_view_num'));
            $totalInfo['sys_order_amount_total'] = array_sum(array_column($list, 'sys_order_amount'));
            $totalInfo['artificial_pay_view_num_total'] = array_sum(array_column($list, 'artificial_pay_view_num'));
            $totalInfo['artificial_order_amount_total'] = array_sum(array_column($list, 'artificial_order_amount'));
            $totalInfo['total_amount_total'] = array_sum(array_column($list, 'total_amount'));
            if (empty($totalInfo['artificial_order_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['artificial_per_amount_total'] = 0;
            } else {
                $totalInfo['artificial_per_amount_total'] = round($totalInfo['artificial_order_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
            if (empty($totalInfo['total_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['per_amount_total'] = 0;
            } else {
                $totalInfo['per_amount_total'] = round($totalInfo['total_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
        }
        $data = [
            'list' => $list,
            'total' => $totalInfo
        ];
        $this->success('获取成功', '', $data);

    }

    //获取客服组统计详情
    public function getGroupStatisticsInfo($id, $accountMiddleIds, $startOpenTime, $endOpenTime,$appBaseId)
    {
        //获取两个日期
        $dateList = printDates($startOpenTime, $endOpenTime);
        $list = [];
        foreach ($dateList as $value) {
            $info['date'] = $value['date'];
            //已分配客服数
            $distributionUserWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_account_middle_id' => ['in', $accountMiddleIds],
                'app_base_id' => $appBaseId
            ];
            $info['distribution_user_num'] = User::where($distributionUserWhere)->count('id');
            //系统生成支付页面
            $sysPayViewWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_group_id' => $id,
                'generate_type' => 1,
                'app_base_id' => $appBaseId
            ];
            $info['sys_pay_view_num'] = \app\partneradmin\model\PayView::where($sysPayViewWhere)->count('id');
            //系统订单支付金额
            $sysOrderWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'generate_type' => 1,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['sys_order_amount'] = Order::where($sysOrderWhere)->sum('real_amount');
            //人工生成支付页面
            $artificialPayViewWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_group_id' => $id,
                'generate_type' => 2,
                'app_base_id' => $appBaseId
            ];
            $info['artificial_pay_view_num'] = \app\partneradmin\model\PayView::where($artificialPayViewWhere)->count('id');;
            //人工支付订单金额
            $artificialOrderWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_group_id' => $id,
                'generate_type' => 2,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['artificial_order_amount'] = Order::where($artificialOrderWhere)->sum('real_amount');
            //计算总金额
            $info['total_amount'] = $info['sys_order_amount'] + $info['artificial_order_amount'];
            //计算人工订单人均
            if (empty($info['artificial_order_amount']) || empty($info['distribution_user_num'])) {
                $info['artificial_per_amount'] = 0;
            } else {
                $info['artificial_per_amount'] = round($info['artificial_order_amount'] / $info['distribution_user_num'], 2);
            }
            //计算人均
            if (empty($info['total_amount']) || empty($info['distribution_user_num'])) {
                $info['per_amount'] = 0;
            } else {
                $info['per_amount'] = round($info['total_amount'] / $info['distribution_user_num'], 2);
            }
            $list[] = $info;
        }
        return $list;
    }
}